#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
APP_ROOT_DIR="$(dirname "$SCRIPT_DIR")"
. "$APP_ROOT_DIR/config.sh"

if [ $# -lt 2 ]; then
	echo "Usage: $0 /path/to/src/firefox x64|arm64|win32" >&2
	exit 1
fi

gecko_path=$1
arch=$2

if [ ! -d "$gecko_path" ]; then
	echo "$gecko_path is not a directory" >&2
	exit 1
fi

# Install required Rust version
rustup toolchain install $RUST_VERSION
if [ $arch = "x64" ]; then
	rust_target=x86_64
elif [ $arch = "arm64" ]; then
	rust_target=aarch64
elif [ $arch = "win32" ]; then
	rust_target=i686
else
	echo "Unknown architecture $arch" >&2
	exit 1
fi
rustup target add $rust_target-pc-windows-msvc
rustup default $RUST_VERSION

cp "$SCRIPT_DIR/mozconfig" "$gecko_path"

if [[ $arch == "arm64" || $arch == "win32" ]]; then
	export Z_ARCH=$arch
	export RUST_TARGET=$rust_target-pc-windows-msvc
fi

cd "$gecko_path"
./mach build
./mach package
